/*------------------------------------------------------------------------
# StartOnLoadService.java - VipApi
# ------------------------------------------------------------------------
# 
# 系统启动加载 默认配置信息
# 
# author    zch
# date  	2014/03/19
# version 	v1.0
# copyright Copyright (C) 2014 wevip.com. All Rights Reserved.
# Websites: http://www.wevip.com
# Technical Support:  Forum - http://www.wevip.com
# 
# 1、新规
#
 */
package cn.com.api.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.api.entity.*;
import cn.com.api.mapper.*;
import cn.com.util.*;

@Service
public class StartOnLoadService {

	@Autowired
	private SystemMapper systemMapper;
	@Autowired
	private ApiT_cityMapper apiT_cityMapper;
	@Autowired
	private ApiNewsMapper apiNewsMapper;
	@Autowired
	private ApiTypeService apiTypeService;
	@Autowired
	private ApiT_brandService apiT_brandService;
	@Autowired
	private ApiT_user_actionMapper apiT_user_actionMapper;
	@Autowired
	private ApiGoodsService apiGoodsService;
	@Autowired
	private ApiT_goods_activityService apiT_goods_activityService;
	@Autowired
	private ApiT_enumsMapper apiT_enumsMapper;
	@Autowired
	private U_cateMapper u_cateMapper;
	@Autowired
	private U_articleMapper u_articleMapper;
	@Autowired
	private U_articleService u_articleService;
	@Autowired
	private ApiT_configurationService apiT_configurationService;
	@Autowired
	private ApiU_linkService apiU_linkService;
	@Autowired
	private ApiU_link_groupService apiU_link_groupService;

	@Autowired
	public static CacheManager manager;

	public void setSystemMapper(SystemMapper systemMapper) {
		this.systemMapper = systemMapper;
	}

	// 数据字典
	public List<ApiT_enums> enum_dict() {
		Cache _cache = manager.getCache("enums");
		Element element = _cache != null ? _cache.get("enums") : null;
		if (element == null) {
			//
			List<ApiT_enums> _enums = apiT_enumsMapper.findT_enumss();
			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			_cache.put(new Element("enums", _enums));
			return _enums;
		} else {
			return (List<ApiT_enums>) element.getValue();
		}
	}

	/**
	 * 清空缓存的数据字典
	 */
	public void enum_dict_clear() {
		Cache _cache = manager.getCache("enums");
		Element element_enums = _cache.get("enums");
		if (element_enums != null)
			_cache.remove("enums");
	}

	public List<U_cate> article_cates() {
		Cache _cache = manager.getCache("article_cates");
		Element element = _cache.get("article_cates");
		if (element == null) {
			// List<U_cate> sorted_first_cates = new ArrayList<U_cate>();
			// List<U_cate> sorted_second_cates = new ArrayList<U_cate>();
			// List<U_cate> sorted_third_cates = new ArrayList<U_cate>();
			// List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId();
			// // 加入一级类
			// for (U_cate cate : u_cates) {
			// if (cate.getParent_id() == 1)
			// sorted_first_cates.add(cate);
			// }
			// // 加入二级类
			// for (U_cate cate : sorted_first_cates) {
			// // 原一级类
			// sorted_third_cates.add(cate);
			// //
			// List<U_cate> u_cates2 =
			// u_cateMapper.findU_catesByParent_id(cate.getId().toString());
			// if (u_cates2.size() > 0) {
			// for (U_cate cate2 : u_cates2) {
			// // 新二级类
			// sorted_third_cates.add(cate2);
			// // 加入三级类
			// List<U_cate> u_cates3 =
			// u_cateMapper.findU_catesByParent_id(cate2.getId().toString());
			// sorted_third_cates.addAll(u_cates3);
			// }
			// }
			// }
			// // 排序后的分类列表
			// for (U_cate cate : sorted_third_cates) {
			// String cate_str = this.cates_str_OrderById(cate);
			// cate.setCate_full_name(cate_str);
			// List<U_article> articles =
			// u_articleService.findU_articlesByCateId(cate.getId().toString());
			// cate.setArticle_count(articles.size());
			// int read_count = 0;
			// for (U_article art : articles) {
			// read_count += art.getRead_count();
			// }
			// cate.setRead_count(read_count);
			// }

			List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId(1);
			_cache.put(new Element("article_cates", u_cates));
			return u_cates;
		} else {
			return (List<U_cate>) element.getValue();
		}
	}

	/**
	 * 清空缓存的数据字典
	 */
	public void article_cates_clear() {
		Cache _cache = manager.getCache("article_cates");
		Element element_enums = _cache.get("article_cates");
		if (element_enums != null)
			_cache.remove("article_cates");
	}

	// /**
	// * 一级和二级分类
	// */
	// public List<U_cate> article_cates_sub() {
	// //
	// List<U_cate> sorted_first_cates = new ArrayList<U_cate>();
	// List<U_cate> sorted_second_cates = new ArrayList<U_cate>();
	// List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId();
	// // 加入一级类
	// for (U_cate cate : u_cates) {
	// if (cate.getParent_id() == 0)
	// sorted_first_cates.add(cate);
	// }
	// // 加入二级类
	// for (U_cate cate : sorted_first_cates) {
	// // 原一级类
	// sorted_second_cates.add(cate);
	// //
	// List<U_cate> u_cates2 =
	// u_cateMapper.findU_catesByParent_id(cate.getId().toString());
	// if (u_cates2.size() > 0) {
	// for (U_cate cate2 : u_cates2) {
	// // 新二级类
	// sorted_second_cates.add(cate2);
	// }
	// }
	// }
	// // 排序后的分类列表
	// for (U_cate cate : sorted_second_cates) {
	// String cate_str = this.cates_str_OrderById(cate);
	// cate.setCate_full_name(cate_str);
	// List<U_article> articles =
	// u_articleService.findU_articlesByCateId(cate.getId().toString());
	// cate.setArticle_count(articles.size());
	// int read_count = 0;
	// for (U_article art : articles) {
	// read_count += art.getRead_count();
	// }
	// cate.setRead_count(read_count);
	// }
	// //
	// return sorted_second_cates;
	// }

	/***
	 * 返回分类结构 含Html
	 * 
	 * @param request
	 * @return
	 */
	public String cates_str_OrderById(U_cate cate) {
		String ret_str = " ";
		// 一级类
		if (cate.getParent_id() == 1) {
			ret_str = "<div class='td_cat'>" + cate.getCate_name() + "</div>";
		} else {
			U_cate parent_cate = u_cateMapper.findU_cateById(Integer
					.valueOf(cate.getParent_id()));
			// 二级类
			if (parent_cate != null && parent_cate.getParent_id() == 0) {
				ret_str = "<div class='td_cat'>" + parent_cate.getCate_name()
						+ "</div><div class='td_cat'> |-- <b>"
						+ cate.getCate_name() + "</b></div>";
			}
			// 三级类
			if (parent_cate != null && parent_cate.getParent_id() != 0) {
				U_cate sub_parent_cate = u_cateMapper.findU_cateById(Integer
						.valueOf(parent_cate.getParent_id()));
				ret_str = "<div class='td_cat'>"
						+ sub_parent_cate.getCate_name() + "</div>";
				ret_str += "<div class='td_cat'> |-- "
						+ parent_cate.getCate_name()
						+ "</div><div class='td_cat'> |-- <b>"
						+ cate.getCate_name() + "</b></div>";
			}
		}
		//
		return ret_str;
	}

	// /**
	// * 一级文章分类
	// */
	// public List<U_cate> article_first_cates() {
	// Cache _cache = manager.getCache("article_first_cates");
	// Element element = _cache.get("article_first_cates");
	// if (element == null) {
	// //
	// List<U_cate> sorted_first_cates = new ArrayList<U_cate>();
	// List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId();
	// // 加入一级类
	// for (U_cate cate : u_cates) {
	// if (cate.getParent_id() == 0)
	// sorted_first_cates.add(cate);
	// }
	// // 排序后的分类列表
	// for (U_cate cate : sorted_first_cates) {
	// String cate_str = this.cates_str_OrderById(cate);
	// cate.setCate_full_name(cate_str);
	// }
	// //
	// _cache.put(new Element("article_first_cates", sorted_first_cates));
	// return u_cates;
	// } else {
	// return (List<U_cate>) element.getValue();
	// }
	// }
	//
	// /***
	// * 文章二级分类
	// *
	// * @return
	// */
	// public List<U_cate> article_second_cates() {
	// Cache _cache = manager.getCache("article_second_cates");
	// Element element = _cache.get("article_second_cates");
	// if (element == null) {
	// //
	// List<U_cate> sorted_first_cates = new ArrayList<U_cate>();
	// List<U_cate> sorted_second_cates = new ArrayList<U_cate>();
	// List<U_cate> sorted_third_cates = new ArrayList<U_cate>();
	// List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId();
	// // 加入一级类
	// for (U_cate cate : u_cates) {
	// if (cate.getParent_id() == 0)
	// sorted_first_cates.add(cate);
	// }
	// // 加入二级类
	// for (U_cate cate : sorted_first_cates) {
	// // 原一级类
	// // sorted_third_cates.add(cate);
	// //
	// List<U_cate> u_cates2 =
	// u_cateMapper.findU_catesByParent_id(cate.getId().toString());
	// if (u_cates2.size() > 0) {
	// for (U_cate cate2 : u_cates2) {
	// // 新二级类
	// sorted_third_cates.add(cate2);
	// }
	// }
	// }
	// // 排序后的分类列表
	// for (U_cate cate : sorted_third_cates) {
	// String cate_str = this.cates_str_OrderById(cate);
	// cate.setCate_full_name(cate_str);
	// }
	// //
	// _cache.put(new Element("article_second_cates", sorted_third_cates));
	// return u_cates;
	// } else {
	// return (List<U_cate>) element.getValue();
	// }
	// }
	//
	// public List<U_cate> article_third_cates() {
	// Cache _cache = manager.getCache("article_third_cates");
	// Element element = _cache.get("article_third_cates");
	// if (element == null) {
	// //
	// List<U_cate> sorted_first_cates = new ArrayList<U_cate>();
	// List<U_cate> sorted_second_cates = new ArrayList<U_cate>();
	// List<U_cate> sorted_third_cates = new ArrayList<U_cate>();
	// List<U_cate> u_cates = u_cateMapper.findU_catesOrderByParentId();
	// // 加入一级类
	// for (U_cate cate : u_cates) {
	// if (cate.getParent_id() == 0)
	// sorted_first_cates.add(cate);
	// }
	// // 加入二级类
	// for (U_cate cate : sorted_first_cates) {
	// // 原一级类
	// // sorted_third_cates.add(cate);
	// //
	// List<U_cate> u_cates2 =
	// u_cateMapper.findU_catesByParent_id(cate.getId().toString());
	// if (u_cates2.size() > 0) {
	// for (U_cate cate2 : u_cates2) {
	// // 新二级类
	// // sorted_third_cates.add(cate2);
	// // 加入三级类
	// List<U_cate> u_cates3 =
	// u_cateMapper.findU_catesByParent_id(cate2.getId().toString());
	// sorted_third_cates.addAll(u_cates3);
	// }
	// }
	// }
	// // 排序后的分类列表
	// for (U_cate cate : sorted_third_cates) {
	// String cate_str = this.cates_str_OrderById(cate);
	// cate.setCate_full_name(cate_str);
	// }
	// //
	// _cache.put(new Element("article_third_cates", sorted_third_cates));
	// return u_cates;
	// } else {
	// return (List<U_cate>) element.getValue();
	// }
	// }

	// 配置信息
	public Map<String, String> dictionaryMap() {
		Cache cache_config = manager.getCache("configs");
		Element element = cache_config.get("configs");
		if (element == null) {
			// 配置信息
			Map<String, String> dictionaryMap = new HashMap<String, String>();
			List<Configuration> configurations = systemMapper
					.getConfigurations("");
			for (Configuration configuration : configurations) {
				if (configuration.getFieldname() != null) {
					dictionaryMap.put(configuration.getFieldname().trim()
							.toUpperCase(), configuration.getFieldvalue()
							.trim());
				}
			}
			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			cache_config.put(new Element("configs", dictionaryMap));
			return dictionaryMap;
		} else {
			return (Map<String, String>) element.getValue();
		}
	}

	// 语言资源信息
	public static Map<String, String> languageMap = new HashMap<String, String>();

	// 开通自营的县市
	public List<ApiT_city> citys() {
		Cache cache_config = manager.getCache("citys");
		Element element = cache_config.get("citys");
		if (element == null) {
			// 开通县市
			List<ApiT_city> citys = apiT_cityMapper.findT_citysByIsOpen(1);
			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			cache_config.put(new Element("citys", citys));
			return citys;
		} else {
			return (List<ApiT_city>) element.getValue();
		}
	}

	// 系统中的用户权限
	public List<ApiT_user_action> user_actions() {
		Cache cache_config = manager.getCache("user_actions");
		Element element = cache_config.get("user_actions");
		if (element == null) {
			// 开通县市
			List<ApiT_user_action> user_actions = apiT_user_actionMapper
					.findT_user_actions();
			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			cache_config.put(new Element("user_actions", user_actions));
			return user_actions;
		} else {
			return (List<ApiT_user_action>) element.getValue();
		}
	}

	// 营销活动分类
	public List<ApiType> promotion_types() {
		Cache cache_config = manager.getCache("promotion_types");
		Element element = cache_config.get("promotion_types");

		List<ApiType> promotion_types = new ArrayList<ApiType>();
		if (element == null) {
			promotion_types = systemMapper.getTypesPromotion();
			cache_config.put(new Element("promotion_types", promotion_types));

		} else {
			promotion_types = (List<ApiType>) element.getValue();
		}
		return promotion_types;
	}

	// 品类-根据id获取所属分类下所有子类数组
	public List<Integer> typesByParentId(String id) {
		Cache cache_config = manager.getCache("typesByParentId");
		Element element = cache_config.get("typesByParentId_" + id);
		List<Integer> count = new ArrayList<Integer>();
		if (element == null) {
			// 品类
			String typeid = "";
			List<Integer> one = new ArrayList<Integer>();

			one = apiTypeService.getGoodTypesByParentType(Integer.parseInt(id));
			for (Integer o : one) {
				count.add(o);
				List<Integer> two = new ArrayList<Integer>();
				two = apiTypeService.getGoodTypesByParentType(o);
				for (Integer t : two) {
					count.add(t);
					List<Integer> three = new ArrayList<Integer>();
					three = apiTypeService.getGoodTypesByParentType(o);
					for (Integer f : three) {
						count.add(f);
					}
				}
			}
			/*
			 * HashSet<Integer> hs = new HashSet<Integer>(count); for (Integer l
			 * : hs) { typeid += l + ","; } goods_type = typeid.split(",");
			 */
			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			cache_config.put(new Element("typesByParentId_" + id, count));
			return count;
		} else {
			return (List<Integer>) element.getValue();
		}
	}

	// 转换数组数据类型
	public String[] int2strList(List<Integer> ints) {
		String[] goods_type = null;
		String typeid = "";

		HashSet<Integer> hs = new HashSet<Integer>(ints);
		for (Integer l : hs) {
			typeid += l + ",";
		}

		goods_type = typeid.split(",");
		return goods_type;
	}

	// 首页分类缓存
	public List<Map<String, Object>> home_types() {
		Cache cache_config = manager.getCache("home_types");
		Element element = cache_config.get("home_types");
		if (element == null) {
			//
			List<Map<String, Object>> types = apiTypeService.getAllGoodsTypes();
			for (Map<String, Object> type : types) {
				Object type_id = type.get("c_code");
				List<Integer> all_child_types_ints = this
						.typesByParentId(type_id.toString());
				String[] all_child_types = this
						.int2strList(all_child_types_ints);
				// 查找子类下所有商品的品牌
				HashMap<String, Object> condition = new HashMap<String, Object>();
				condition.put("types", all_child_types);
				List<Map<String, Object>> brands = apiT_brandService
						.findT_brandsByTypeId(condition);
				//
				type.put("brands", brands);
			}
			cache_config.put(new Element("home_types", types));
			return types;
		} else {
			return (List<Map<String, Object>>) element.getValue();
		}
	}

	// 首页推荐商品
	public List<Map<String, Object>> home_goods_promotion() {
		Cache cache_config = manager.getCache("home_goods_promotion");
		Element element = cache_config.get("home_goods_promotion");
		if (element == null) {
			//
			String currentPage = "1";
			PageInfo pageInfo = new PageInfo();
			pageInfo.setCurrentPage(Integer.valueOf(currentPage));
			//
			Map<String, Object> conditions = new HashMap<String, Object>();
			// "1001011367"; //每周上新 "1001011369"; //推荐商品 "1001011368"; //一元试用
			conditions.put("act_type_id", "1001011369");
			// conditions.put("city_id", city_id);
			List<Map<String, Object>> goods_activity_list = apiT_goods_activityService
					.searchActivityGoodsInfo(conditions, pageInfo);

			cache_config.put(new Element("home_goods_promotion",
					goods_activity_list));
			return goods_activity_list;
		} else {
			return (List<Map<String, Object>>) element.getValue();
		}
	}

	// 首页品类下商品-根据分类id获取
	public List<ApiGoods> home_goodsByTypeId(String type_id) {
		Cache cache_config = manager.getCache("home_goodsByTypeId");
		Element element = cache_config.get("home_goodsByTypeId_" + type_id);
		List<ApiGoods> goods_list = null;
		if (element == null) {

			Map<String, Object> conditions = new HashMap<String, Object>();
			// 1按销量；2按价格；3按新品；4按评价
			conditions.put("sortType", 3);
			conditions.put("type", type_id);
			conditions.put("isZiYing", true);
			conditions.put("cEnable", true);
			conditions.put("status", 1); // 商户商品状态 0:未发布 1:在售中 2:已下架
			PageInfo pageInfo = new PageInfo();
			pageInfo.setCurrentPage(1);
			goods_list = apiGoodsService.searchGoods(conditions, pageInfo);

			// 向Cache对象里添加Element元素，Element元素有key，value键值对组成
			cache_config.put(new Element("home_goodsByTypeId_" + type_id,
					goods_list));
			return goods_list;
		} else {
			return (List<ApiGoods>) element.getValue();
		}
	}

	// 一级菜单信息对象
	public List<ApiType> oneList2222() {
		Cache cache_config = manager.getCache("oneList");
		Element element = cache_config.get("oneList");

		List<ApiType> oneList = new ArrayList<ApiType>();
		if (element == null) {
			/* begin */

			// 全部菜单类型 到3级菜单
			Map<String, ApiType> mapTemp = new LinkedHashMap<String, ApiType>();
			// 入驻类型到3级菜单
			Map<String, ApiType> rzTemp = new LinkedHashMap<String, ApiType>();
			// 子级菜单集合
			Map<String, Map<String, List<ApiType>>> childrenMap = new HashMap<String, Map<String, List<ApiType>>>();

			// 菜单
			List<ApiType> typelist = systemMapper.getTypeList();
			int oldtag = 0;

			List<ApiType> list = null;
			/** 让最后一组对象加入到map中,设置虚拟最大类型对象 */
			ApiType a = new ApiType();
			a.setcBelong(999999999);
			typelist.add(a);
			//
			Map<String, List<ApiType>> temObj = new LinkedHashMap<String, List<ApiType>>();
			Map<String, String> menuMap = ViewUtils
					.transToMenuMap(dictionaryMap());
			for (ApiType bean : typelist) {
				// 一級菜單
				if (bean.getcBelong() == 0) {
					if ("View1".equals(menuMap.get(bean.getcCode() + ""))) {// 1-第一类返回View1
						bean.setView("View1");
					} else if ("View2"
							.equals(menuMap.get(bean.getcCode() + ""))) {// 家政服务
						bean.setView("View2");
					} else if ("View3"
							.equals(menuMap.get(bean.getcCode() + ""))) {// 外卖
						bean.setView("View3");
					} else if ("View4"
							.equals(menuMap.get(bean.getcCode() + ""))) {// 鲜花蛋糕
						bean.setView("View4");
					} else if ("View5"
							.equals(menuMap.get(bean.getcCode() + ""))) {// 医疗保健-教育
						bean.setView("View5");
					}

					oneList.add(bean);
					String m = Utils.TYPE_LEVEL + "_" + bean.getcCode();
					mapTemp.put(m, bean);
					continue;
				}
				// 当父级ID不一样时
				if (oldtag != bean.getcBelong()) {
					if (list != null) {
						// 子级类型加入
						String keyv = Utils.TYPE_LEVEL + "_" + oldtag;
						// 当
						if (mapTemp.containsKey(keyv)) {
							(mapTemp.get(keyv)).setListType(list);
						}
						temObj.put(keyv, list);
					}
					list = new ArrayList<ApiType>();
				}
				oldtag = bean.getcBelong();
				list.add(bean);
			}

			// 将三级菜单存入列表中
			@SuppressWarnings("rawtypes")
			Iterator it = mapTemp.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				ApiType value = mapTemp.get(key);
				List<ApiType> l = value.getListType();

				// 当有二级菜单时
				if (l != null) {
					int i = 0;
					for (ApiType apitype : l) {
						if (apitype.getcBelong() == 8) {
							System.out.println(apitype);
						}
						// 二级类型key
						String keyv = Utils.TYPE_LEVEL + "_"
								+ apitype.getcCode();
						if (temObj.containsKey(keyv)) {
							apitype.setListType(temObj.get(keyv));
							l.set(i, apitype);
						}
						i++;
					}
				}

				// 筛选自营商户
				if (value.getcIsziying() == 1) {
					rzTemp.put(key, value);
				}
			}

			cache_config.put(new Element("oneList", oneList));
			/* end */

		} else {
			oneList = (List<ApiType>) element.getValue();
		}
		return oneList;
	}

	// List<ApiNews> adsList = new ArrayList<ApiNews>();

	public static List<ApiT_configuration> configurationList = new ArrayList<ApiT_configuration>();
	public static List<Map<String, Object>> articlesList = new ArrayList<Map<String, Object>>();
	public static List<Map<String, Object>> linkList = new ArrayList<Map<String, Object>>();

	/**
	 * 加载配置信息
	 */
	public void loadData() {
		try {
			// 指定ehcache.xml的位置
			manager = new CacheManager();
			// // 文章信息
			// articlesList = u_articleService.allfindU_articles();
			// 系统配置
			configurationList = apiT_configurationService
					.findT_configurations();
			// 友情链接
			// List<ApiU_link_group> findU_link_groups = apiU_link_groupService
			// .findU_link_groups();
			// for (ApiU_link_group apiU_link_group : findU_link_groups) {
			// Map<String, Object> map = new HashMap<String, Object>();
			// map.put("groupname", apiU_link_group.getName());
			// List<ApiU_link> linkslist = apiU_linkService
			// .findU_linksByGroupId(Integer.valueOf(apiU_link_group
			// .getId()));
			// map.put("links", linkslist);
			// linkList.add(map);
			// }

			// 加载商城分类
			Cache cache_config = manager.getCache("mall_types");
			List<ApiType> mall_types = apiTypeService.findTypes();
			cache_config.put(new Element("mall_types", mall_types));
		} catch (Exception e) {

		}
	}

	// 首页分类缓存
	public List<ApiType> mall_types() {
		Cache cache_config = manager.getCache("mall_types");
		Element element = cache_config.get("mall_types");
		if (element == null) {
			List<ApiType> mall_types = apiTypeService.findTypes();
			cache_config.put(new Element("mall_types", mall_types));
			return mall_types;
		} else {
			return (List<ApiType>) element.getValue();
		}
	}
}
